import { _decorator, Color, Component, instantiate, Label, Node, Prefab, RichText, Sprite, SpriteFrame } from 'cc';
import { Soldier } from '../entity/Soldier';
import { Advanced, UpGradeType } from '../entity/Advanced';
import { Building, DiamondConsume, EventOper } from '../entity/Buildings';
import { UserInfo } from '../common/UserInfo';
import { Utils } from '../common/Utils';
import VillageApi from '../api/VillageApi';
import { Events } from '../entity/Events';
import { UIManager } from '../common/UIManager';
import { DevelopMaxLevelBlock } from './DevelopMaxLevelBlock';
import { EventManager } from '../event/EventManager';

const { ccclass, property } = _decorator;

@ccclass('DevelopUpGradeBlock')
export class DevelopUpGradeBlock extends Component {
    @property(Sprite)
    cover: Sprite
    @property(Label)
    tittle: Label
    @property(Label)
    condition: Label
    @property(Label)
    wood: Label
    @property(Label)
    mud: Label
    @property(Label)
    iron: Label
    @property(Label)
    food: Label
    @property(Label)
    time: Label
    @property(Label)
    attack: Label
    @property(Label)
    level: Label
    @property(Label)
    nextAttack: Label
    @property(Label)
    nextLevel: Label
    @property(Node)
    upGradeBtn: Node

    @property(Label)
    typeName: Label

    @property(Label)
    nextTypeName: Label

    @property(Label)
    countTittle: Label

    @property(Label)
    countTime: Label


    @property(Node)
    speedBtn: Node

    @property(Prefab)
    DevelopMaxLevelBlock: Prefab
    @property(SpriteFrame)
    attackImg:SpriteFrame
    @property(SpriteFrame)
    defenseImg:SpriteFrame

    private red:Color = Utils.Red
    private advanced: Advanced
    private building: Building

    private offTime: number = 0
    start() {
        this.upGradeBtn.on(Node.EventType.TOUCH_END, this.onUpGrade, this)
        this.speedBtn.on(Node.EventType.TOUCH_END, this.onSpeed, this)
    }

    /**
     * 设置攻击等级的数据
     * @param soldier 
     */
    setDataAttack(soldier: Soldier) {
        this.advanced = soldier.getAttackAdvanced()
        this.building = this.advanced.building
        this.tittle.string = '攻击强化'
        this.typeName.string = '攻击力'
        this.nextTypeName.string = '攻击力'
        this.cover.spriteFrame = this.attackImg

        this.setData()
    }

    /**
     * 设置防御等级的数据
     * @param soldier 
     */
    setDataDefense(soldier: Soldier) {
        this.advanced = soldier.getDefenseAdvanced()
        this.building = this.advanced.building
        this.tittle.string = '防御强化'
        this.typeName.string = '防御力'
        this.nextTypeName.string = '防御力'
        this.cover.spriteFrame = this.defenseImg

        this.setData()



    }

    setData() {
        let soldier = this.advanced.soldier
        let building = this.advanced.building
        if (building.level > 0) {
            if (building.level > soldier.attackLevel) {
                this.condition.string = `${building.name}${building.level}级，最高可强化至${building.level}级`
            } else {
                this.condition.string = `${building.name}${building.level}级，需要升级${building.name}`
                this.condition.color = this.red
            }
        } else {
            this.condition.string = `需建造${building.name}`
            this.condition.color = this.red
        }
        this.level.string = this.advanced.level + ''
        this.nextLevel.string = (this.advanced.level + 1) + ''
        this.attack.string = '+' + this.advanced.addition * 100 + '%'
        this.nextAttack.string = '+' + this.advanced.additionNext * 100 + '%'

        this.wood.string = Utils.bigNumberTransform(this.advanced.wood)
        this.mud.string = Utils.bigNumberTransform(this.advanced.mud)
        this.iron.string = Utils.bigNumberTransform(this.advanced.iron)
        this.food.string = Utils.bigNumberTransform(this.advanced.food)
        this.time.string = Utils.secondToStr(Math.floor(this.advanced.time / UserInfo.instance.speed))

        let villageData = UserInfo.instance.villageData
        let food = villageData.res.food_reserve
        let iron = villageData.res.iron_reserve
        let wood = villageData.res.wood_reserve
        let mud = villageData.res.mud_reserve

        if (food < this.advanced.food) {
            this.food.color = Color.RED
        }
        if (iron < this.advanced.iron) {
            this.iron.color = Color.RED
        }
        if (wood < this.advanced.wood) {
            this.wood.color = Color.RED
        }
        if (mud < this.advanced.mud) {
            this.mud.color = Color.RED
        }


        let event = this.advanced.getEvent()
        if (event) {
            this.upGradeBtn.active = false
            this.countTittle.node.active = true
            this.countTime.node.active = true
            this.speedBtn.active = true
        } else {
            this.upGradeBtn.active = true
            this.countTittle.node.active = false
            this.countTime.node.active = false
            this.speedBtn.active = false
        }
        // 开启升级事件的倒计时
        this.countDown(event)
        //最大等级的特殊处理
        this.setMaxLevelData()

    }

    countDown(event) {


        this.unschedule(this.updateTime)
        if (!event) {
            return
        }

        let eStartTime = event.eStartTime
        this.offTime = eStartTime - Math.floor(UserInfo.instance.serverTime / 1000)
        if (this.offTime <= 0) {
            return
        }

        this.countTime.string = Utils.secondToStr(this.offTime)
        this.schedule(this.updateTime, 1, this.offTime - 1)
    }

    updateTime() {
        this.offTime--
        this.countTime.string = Utils.secondToStr(this.offTime)

        if (this.offTime <= 0) {
            // 倒计时完成
            // 清除事件，刷新页面
            this.advanced.upGradeComplete()
        }
    }

    /**如果到了最大等级，将做一些特殊的处理 */
    setMaxLevelData() {
        console.log(this.node.getSiblingIndex())
        if (this.advanced.level < this.advanced.maxLevel) {
            return
        }

        let maxLevelNode = instantiate(this.DevelopMaxLevelBlock)
        this.node.parent.addChild(maxLevelNode)
        if (this.advanced.type == UpGradeType.Attack) {

            maxLevelNode.getComponent(DevelopMaxLevelBlock).setDataAttack(this.advanced.soldier)
            maxLevelNode.setSiblingIndex(0)
        }

        if (this.advanced.type == UpGradeType.Defense) {
            maxLevelNode.getComponent(DevelopMaxLevelBlock).setDataDefense(this.advanced.soldier)
            maxLevelNode.setSiblingIndex(10)
        }


        this.node.destroy()
    }

    async onUpGrade() {
        if (!this.advanced.isEnoughRes) {
            this.upGradeBtn.getChildByName('Label').getComponent(Label).string = '资源不足'
        }

        if (!this.advanced.isCanUpGrade) {
            return
        }

        await UIManager.instance.showLoading()
        let res = await VillageApi.gradingSoldier(this.advanced.soldier.soldierIndex + 1, this.advanced.type, true)
        UIManager.instance.closeLoading()
        console.log(`升级兵种id=${this.advanced.soldier.id}，${this.advanced.soldier.name}， ${this.advanced.type}`, res)

        await UserInfo.instance.refreshVillageDetail()
        this.setData()
    }

    async onSpeed() {
        let event = this.advanced.getEvent()
        let param = {
            ac: EventOper.SPEED_BUILD,
            eid: event.eHandle
        }

        await UIManager.instance.showLoading()
        let res = await VillageApi.eventOper(param)
        UIManager.instance.closeLoading()
        console.log(`加速升级，ac =${param.ac} ,del =${param.eid} `, res)

        // 清除事件，刷新页面
        this.advanced.upGradeComplete()
    }
}


